import { Component, OnInit, ViewChild, ElementRef, Input, ChangeDetectionStrategy, SimpleChanges } from '@angular/core';
import { GanttService } from '../../services/gantt-chart/gantt.service';
import { GanttHelperService } from '../../services/gantt-chart/gantt-helper.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import * as moment from 'moment';
import { GanttRequestService } from '../../services/gantt-chart/gantt-request.service';
import { PREVTYPE } from '../../services/gantt-chart/gantt.config';
import { GanttProjectModel } from '../../services/gantt-chart/gantt-project.model';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { FileHelper } from '../../common/helper/file-helper';
import { HOSTURL } from '../../config';
import { ModelService } from '../../services/model/model.service';
import { UpdateModelService } from '../../services/model/update-model.service';
import { MessageService } from '@src/app/services/message.service';
import { SchedulePlugin } from '@src/app/services/model/model.plugin';


@Component({
  selector: 'app-gantt-chart',
  templateUrl: './gantt-chart.component.html',
  styleUrls: ['./gantt-chart.component.scss']
})
export class GanttComponent implements OnInit {
  @ViewChild('taskbox', { static: false }) public taskbox: ElementRef;
  @ViewChild('ganttContainer', { static: true }) public ganttContainer: ElementRef;
  public isFold = false;
  public leftPanel: any = {};
  public rightPanel: any = {};
  public lastScrollTop: 0;
  public scrollListHeight: number;
  public resizeBarWith = 3;
  public scrollBarWith = 6;
  public rowHeight = 36;
  public bottomHeight = 230;
  public PREVTYPE: any = PREVTYPE;

  public startX: number;
  public overDragWidth: number;
  public preDragWidth:number = 0;

  // 导入Project
  public uploadProjectView = false;
  public uploadForm: {
    uploadTitle: string,
    uploadMMP: File
  };
  // 新建project
  public ganttCreateView = false;
  public createForm: GanttProjectModel;
  public ganttEditView = false;
  public editForm: GanttProjectModel;
  public isOkLoading = false;
  // 进度
  public schedulePnlStyleModel: any = {
    width: 0
  };
  public isScheduleShow = false

  public ganttListView = false;

  public get topPnlStyle() {
    let container = this.ganttContainer.nativeElement.clientHeight || 875;
    return {
      height: container - 40 - this.bottomHeight + 'px'
    };
  }

  public get bottomPnlStyle() {
    return {
      height: this.bottomHeight + 'px'
    };
  }


  public get leftPnlStyle() {
    return {
      width: this.leftPanel.width + "px"
    };
  }
  public get rightPnlStyle() {

    let container = this.ganttContainer.nativeElement.clientWidth || 800;
    this.rightPanel.width = container - this.resizeBarWith - this.leftPanel.width - this.scrollBarWith;
    return {
      width: this.rightPanel.width + 'px'
    };
  }
  public constructor(
    private elementRef: ElementRef,
    public ganttService: GanttService,
    public ganttHelperService: GanttHelperService,
    private message: NzMessageService,
    private ganttReqsev: GanttRequestService,
    private modelSev: NzModalService,
    private router: Router,
    private modelService: ModelService,
    private ganttRequestSev: GanttRequestService,
    private routeInfo: ActivatedRoute,
    private updateModelService: UpdateModelService,
    private messageService: MessageService,
    private schedulePlugin: SchedulePlugin,
  ) {
  }
  public ngOnInit() {
    // 初始化
    let container = this.schedulePnlStyleModel.width || 800;
    this.leftPanel.width = (container - this.resizeBarWith - this.scrollBarWith) / 2;
    this.rightPanel.width = this.leftPanel.width;
    this.uploadForm = {
      uploadMMP: null,
      uploadTitle: ''
    };

    let companyName = JSON.parse(window.localStorage.getItem('project')).companyName;
    let name = JSON.parse(window.localStorage.getItem('APDInfo'))['userName'];
    this.createForm = new GanttProjectModel({
      title: '',
      dateFormat: null,
      author: name,
      company: companyName
    });
    // this.rightPanel = container - this.resizeBarWith - this.leftPanel.width + "px";
    // this.leftPanel.width = container - this.resizeBarWith - this.rightPanel.width;

    // 设置假task列表高度
    if (this.ganttService.allTasks) {
      this.scrollListHeight = this.ganttService.allTasks.length * this.rowHeight + this.scrollBarWith;
    }
    this.messageService.get().subscribe((result) => {
      if (result === 'scheduleClick') {
        this.isScheduleShow = !this.isScheduleShow;
        if (this.isScheduleShow) {
          console.log(this.overDragWidth)
          this.messageService.send({ganttOpen:true})
          this.schedulePnlStyleModel.width = this.overDragWidth?this.overDragWidth:800;
        } else {
          this.messageService.send({ganttOpen:false})
          this.schedulePnlStyleModel.width = 0;
        }
      }
      if (result && result.opt === 'addTask') {
        console.log("生成了一个子任务：gantt-chart.subscribe.addTaskHandle")
        this.ganttService.addTaskHandle('addNewTask');
      }
    });
  }
  // 进度模块
  public get schedulePnlStyle() {
    return {
      width: this.schedulePnlStyleModel.width + 'px',
      height: '100%'
    };
  }

  public setStartX(e: any) {
    this.startX = e.clientX;
    console.log('mousedown')
  }

  public dragstartHandler(e: any, model?: string) {
    this.messageService.send({ dragStart: true })
    e.stopPropagation();
    e.preventDefault();
    //console.log(e);
    let startX = e.clientX;
    this.updateModelService.showPullMask = true;
    this.overDragWidth = this.schedulePnlStyleModel.width;
    let dragHandler = (e) => {
      //设置拖动边界
      if(e.clientX < 250) return;
      //上次窗口位置
      if(this.preDragWidth == 0) this.preDragWidth = this.schedulePnlStyleModel.width;
      //移动窗口
      e.stopPropagation();
      e.preventDefault();
      this.schedulePnlStyleModel.width -= (e.clientX - startX);
      startX = e.clientX;
      this.overDragWidth = this.schedulePnlStyleModel.width;
      //计算移动百分比
      if(e.clientX < 1600){
        let movePercent = this.GetPercent(this.overDragWidth - this.preDragWidth,document.body.clientWidth);
        if(movePercent < 0 && e.clientX < 1000) return;
        if(movePercent > 0 && e.clientX > 1400) return;
        this.messageService.send({MovePercent:movePercent})
      }

      this.preDragWidth = this.overDragWidth;
    };

    let dragendHandler = (e) => {
      this.updateModelService.showPullMask = false;
      this.messageService.send({ dragStart: false })
      console.log('removeevent');
      document.documentElement.removeEventListener('mousemove', dragHandler, false);
      document.documentElement.removeEventListener('mouseup', dragendHandler, false);
    };
    document.documentElement.addEventListener('mouseup', dragendHandler, false);
    document.documentElement.addEventListener('mousemove', dragHandler, false);

  }

  //计算百分比
  GetPercent(num, total) {
    num = parseFloat(num);
    total = parseFloat(total);
    if (isNaN(num) || isNaN(total)) {
        return "-";
    }
    return total <= 0 ? "0" : ((Math.round((num / total * 10000))) / 100.00);
  }

  toggleCollapsed(type) {
    if (type === 'shrink') {
      this.isScheduleShow = false
      this.schedulePnlStyleModel.width = 0
      this.schedulePlugin._button.check = 0
      this.messageService.send({ganttOpen:false})
    } else if (type === 'expand') {
      this.isScheduleShow = true
      this.schedulePnlStyleModel.width = 800
      this.schedulePlugin._button.check = 1
    }
  }
  // 进度模块

  public async downloadXML() {
    if (this.ganttService.currentGantt.id) {
      let id = this.ganttService.currentGantt.id;
      let url = `${HOSTURL}/mpp/api/v1/mpp/export/${id}`;
      FileHelper.download('Project', url);
    } else {
      this.message.error('未打开项目，请先打开一个项目');
    }
  }

  public async showGanttList() {
    let list = await this.ganttReqsev.getGanttList();
    this.ganttService.ganttList = [];
    list.forEach((element) => {
      this.ganttService.ganttList.push(new GanttProjectModel({
        id: element.id,
        parentId: element.parentId,
        calendars: element.calendars,
        creationDate: element.creationDate,
        title: element.title,
        startDate: element.startDate,
        finishDate: element.finishDate
      }));
    });
    console.log(this.ganttService.ganttList);
    this.ganttListView = true;
  }

  /**
   * 创建gantt
   */
  public createNewGantt() {
    this.ganttCreateView = true;
    let companyName = JSON.parse(window.localStorage.getItem('project')).companyName;
    let name = JSON.parse(window.localStorage.getItem('APDInfo'))['userName'];
    this.createForm = new GanttProjectModel({
      dateFormat: null,
      author: name,
      company: companyName
    });
  }

  public async submitCreateGantt() {
    let createForm = this.createForm.toCreateJson();
    console.log(createForm);
    if (!createForm) {
      this.message.error('进度名称不能为空');
      return;
    }
    let ganttId = await this.ganttReqsev.postGantt(createForm);
    if (ganttId) {
      this.message.success('创建成功');
      let projectId = JSON.parse(window.localStorage.getItem('project')).id;
      this.router.navigate([`/inner/project/${projectId}/model`], { queryParams: { info: 'project', id: ganttId } })
      // this.router.navigate([`project/${projectId}/model-page/${this.modelService.modelId}/ganttChart`], { queryParams: { id: ganttId } });
      this.ganttCreateView = false;
      //this.messageService.send({ opt: "addTask" })
    } else {
      this.message.error('创建失败');
    }
  }

  public editGantt(gantt) {
    console.log(gantt);
    let dateFormat = [];
    dateFormat[0] = gantt.startDate;
    dateFormat[1] = gantt.finishDate;
    let name = JSON.parse(window.localStorage.getItem('APDInfo'))['userName'];
    this.editForm = new GanttProjectModel({
      id: gantt.id,
      title: gantt.title,
      dateFormat,
      author: name
    });
    console.log(this.editForm);
    // this.editForm = gantt;
    this.ganttEditView = true;
  }

  public async submitEditGantt() {
    let editForm = this.editForm.toCreateJson();
    if (!editForm.Title) {
      this.message.error('进度名不可为空');
      return
    }
    let res = await this.ganttReqsev.updateGantt(this.editForm.id, editForm);
    // if (res.success) {
    this.message.success('提交成功');
    this.showGanttList();
    let gantt = await this.ganttRequestSev.getGanttInfo(this.ganttService.currentGantt.id);
    this.ganttService.currentGantt.title = gantt.title;
    this.ganttEditView = false;
    // } else {
    //   this.message.error('提交失败');
    // }
  }

  /**
   * 上传gantt
   */
  public importMMPHandle() {
    this.uploadProjectView = true;
  }

  /**
   * 删除gantt
   * @param id 
   */
  public deleteGantt(ganttId) {
    if (ganttId == this.ganttService.currentGantt.id) {
      this.message.error('不能删除当前打开的进度');
      return;
    }
    this.modelSev.confirm({
      nzTitle: '确认删除该项目？',
      nzOnOk: async () => {
        await this.ganttReqsev.deleteGantt(ganttId);
        this.showGanttList();
      }
    });
  }


  /**
   * 跳转到进度
   * @param gantt 
   */
  public async routerToGantt(gantt) {
    const projectId = JSON.parse(window.localStorage.getItem('project')).id;
    // history.pushState('','',`/inner/project/${projectId}/model?info=project&id=${gantt.id}`)
    this.router.navigate([`/inner/project/${projectId}/model`], { queryParams: { info: 'project', id: gantt.id } })
    // this.router.navigate([`/inner/oraganization/department`])
    this.ganttListView = false;
  }

  /**
   * 上传mpp
   */
  public async uploadMPPHandle() {
    if (this.uploadForm.uploadTitle == '') {
      this.message.error('请输入进度名称');
      return;
    }
    if (!this.uploadForm.uploadMMP) {
      this.message.error('请选择导入的project文件');
      return;
    }
    this.isOkLoading = true;
    console.log(this.uploadForm);
    let mpp = await this.ganttReqsev.uploadMMP(this.uploadForm);
    if (mpp) {
      console.log(mpp);
      // let projectId = window.localStorage.getItem('TenantId');
      // this.router.navigate([`project/${projectId}/model-page/${this.modelService.modelId}/ganttChart`], { queryParams: { id: mpp.Id } });
      let projectId = JSON.parse(window.localStorage.getItem('project')).id;
      this.router.navigate([`/inner/project/${projectId}/model`], { queryParams: { info: 'project', id: mpp.id } })
      this.message.success('导入成功');
      this.uploadForm = {
        uploadMMP: null,
        uploadTitle: ''
      };
    } else {
      this.message.error('导入失败');
    }
    this.isOkLoading = false;
    this.uploadProjectView = false;
  }

  public selectFile(event: any) {
    event = event || window.event;
    if (!event || !event.target || !event.target.files) {
      return;
    }
    let files = event.target.files;
    this.uploadForm.uploadMMP = files[0];
    console.log(this.uploadForm.uploadMMP);
  }

  public ngAfterViewInit() {
    setTimeout(() => {
      this.getViewArea();
    }, 100);
  }

  /**
   * get showTasks's length & canvas view height
   */
  public getViewArea() {
    this.ganttService.resizeBarHandle(this.taskbox.nativeElement.clientHeight);
    // 50：日历高度； 20：底部滚动条高度
    this.ganttService.canvasHeight = this.taskbox.nativeElement.clientHeight - 50 - this.scrollBarWith;
  }

  public switchBottom(type: string) {
    switch (type) {
      case 'down':
        this.bottomHeight = 40;
        this.isFold = true;
        setTimeout(() => {
          this.getViewArea();
        }, 500);
        break;
      case 'up':
        this.bottomHeight = 300;
        this.isFold = false;
        setTimeout(() => {
          this.getViewArea();
        }, 500);
        break;
      default:
        break;
    }

  }

  public getScrollHeight() {
    let scrollListHeight = 0;
    if (this.ganttService.allTasks) {
      // 36： 一个task的高度
      scrollListHeight = this.ganttService.getAllTaskAfterFold().length * (this.rowHeight + 1);
    }
    return scrollListHeight;
  }

  // 窗口缩放
  public onWindowResize(event) {
    this.getViewArea();
    this.rightPanel.width = this.ganttContainer.nativeElement.clientWidth - this.leftPanel.width - this.resizeBarWith - this.scrollBarWith;
  }

  /**
   * 
   * @param e 
   */
  public scrollHandler(e) {
    let IsDown = false;
    let scrollTop = e.target.scrollTop;
    scrollTop > this.lastScrollTop ? IsDown = true : IsDown = false;
    if (IsDown) {
      let targetTop = Math.ceil(scrollTop / this.rowHeight) * this.rowHeight;
      e.target.scrollTop = targetTop;
    } else {
      let targetTop = Math.floor(scrollTop / this.rowHeight) * this.rowHeight;
      e.target.scrollTop = targetTop;
    }
    this.lastScrollTop = scrollTop;
    let starIndex = Math.floor(this.lastScrollTop / this.rowHeight);
    this.ganttService.scrollHandle(starIndex);
  }

  /**
   * 鼠标滚动事件
   * @param e 
   * 控制假滚动条滚动
   */
  public mousewheelhandler(e) {
    let o = this.elementRef.nativeElement.querySelector('.scrollBar');
    o.scrollTop = o.scrollTop + e.deltaY / 100 * this.rowHeight;
  }

  /**
   * 新建项目
   * @param group 
   */
  public changeStartDate(group: { name: string, startDate: any, endDate: any }) {
    let startDate = moment(group.startDate).unix();
    let endDate = moment(group.endDate).unix();
    if (!group.endDate) {
      group.endDate = startDate;
      return;
    } else {
      if (startDate > endDate) {
        group.endDate = startDate;
        return;
      }
    }
  }

  public changeEndDate(group: { name: string, startDate: any, endDate: any }) {
    let startDate = moment(group.startDate).unix();
    let endDate = moment(group.endDate).unix();
    if (!group.startDate) {
      group.startDate = endDate;
      return;
    } else {
      if (endDate < startDate) {
        group.startDate = endDate;
        return;
      }
    }
  }

  public hideProgressModal = (e) => {
    this.ganttService.newGanttModalView = false;
  }
  public deletDate(index: number, exceptDate) {
    exceptDate.splice(index, 1);
  }
  public addDate(exceptDate) {
    exceptDate.push(
      { name: '', startDate: null, endDate: null }
    );
  }
  public createMessage = (type, text) => {
    this.message.create(type, text);
  }

  public rulesForNewProject = (newGanttModel) => {
    if (newGanttModel.ganttName == '') {
      this.createMessage('error', '项目名称不能为空');
      return false;
    } else if (!newGanttModel.startDate) {
      this.createMessage('error', '开始时间不能为空');
      return false;
    } else if (!newGanttModel.endDate) {
      this.createMessage('error', '结束时间不能为空');
      return false;
    } else {
      if (newGanttModel.exceptDate.length > 0) {
        let checkName = newGanttModel.exceptDate.findIndex((element) => {
          return element.name === '';
        });
        let checkDate = newGanttModel.exceptDate.findIndex((element) => {
          return element.startDate == null;
        });
        if (checkName !== -1) {
          this.createMessage('error', '例外日期名称不能为空');
          return false;
        } else if (checkDate !== -1) {
          this.createMessage('error', '例外日期不能为空');
          return false;
        } else {
          return true;
        }
      } else {
        return true;
      }

    }
  }

  // handleProgressOk() {
  //   let newGanttModel = this.ganttService.newGanttModel
  //   if (this.rulesForNewProject(newGanttModel)) {
  //     console.log(newGanttModel.toCreateJson())
  //     this.ganttService.addNewProgress(newGanttModel).then((res) => {
  //       console.log(res)
  //       if (res.code && res.code === 1) {
  //         this.createMessage('success', '提交成功');
  //         setTimeout(() => {
  //           this.ganttService.newGanttModalView = false;
  //         }, 500);
  //       }
  //       // this.ganttService.getGanttList();
  //     })
  //   }
  // }

}
